<template>
  <div class="dialog-form">
    <el-form ref="taskRef" :model="form" :rules="rules" label-width="80px">
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入任务名称" :maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属公司" prop="companyId">
            <el-tree-select
              v-model="form.companyId"
              :data="companyList"
              :render-after-expand="true"
              :props="treeProps"
              node-key="id"
              :default-expanded-keys="expandedKeys"
              @change="handleCompanyChange"
              check-strictly
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="巡更人" prop="userId">
            <el-select v-model="form.userId" placeholder="请选择巡更人" :disabled="!form.companyId">
              <el-option
                v-for="item in userList"
                :key="item.user_id"
                :label="item.user_name"
                :value="item.user_id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务周期" prop="dateRange">
            <el-date-picker 
              type="daterange" 
              v-model="form.dateRange" 
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" 
              :style="{width: '100%'}" 
              start-placeholder="开始日期" 
              end-placeholder="结束日期"
              range-separator="至" 
              clearable 
              :disabled-date="handleDisabledDate" 
              :disabled="taskCycle">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="巡更日期" prop="patrolDate">
            <el-select v-model="form.patrolDate" multiple collapse-tags placeholder="请选择巡更日期">
              <el-option
                v-for="item in patrol_date"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="巡更时间" prop="timeRange">
          <el-time-picker v-model="form.timeRange" is-range format="HH:mm" value-format="HH:mm"
                          :style="{width: '100%'}" start-placeholder="开始时间" end-placeholder="结束时间" range-separator="至"
                          clearable></el-time-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车辆线路" prop="lineId">
            <el-select 
              v-model="form.lineId" 
              multiple collapse-tags 
              placeholder="请选择线路" 
              @visible-change="handleLineChange"
              @remove-tag="getBusNo(form.lineId, 1)">
              <el-option
                v-for="item in lineList"
                :key="String(item.id)"
                :label="item.lineName"
                :value="String(item.id)"
                :disabled="item.status == 2"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车辆编号" prop="busNoId">
            <el-select v-model="form.busNoId" multiple collapse-tags placeholder="请选择车辆编号">
              <el-option
                v-for="item in busNo"
                :key="String(item.id)"
                :label="item.bus_no"
                :value="String(item.id)"
                :disabled="item.status == 2"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="巡更项目" prop="projectId">
            <el-select v-model="form.projectId" placeholder="请选择巡更项目" @change="handleProjectChange">
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="item.status == 2"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.projectId">
          <el-form-item label="检查标准">
            <el-input v-model="projectStandard" readonly type="textarea" :rows="5" />
          </el-form-item>
        </el-col>
       <!-- <el-col :span="12">
         <el-form-item label="任务状态" prop="status" required>
           <el-switch
             v-model="form.status"
             inline-prompt
             :active-value="1"
             :inactive-value="2"
             inactive-text="禁用"
             active-text="启用"
           />
         </el-form-item>
       </el-col> -->
      </el-row>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onConfirm">确认</el-button>
    </div>
  </div>
</template>

<script setup>
import { getPatrolTask, addPatrolTask, updatePatrolTask, getSelectData } from "@/api/patrol/task"
import { getAllCompanies } from '@/api/company/company'
import { listLine } from "@/api/bus/line"
import { listPatrolProject } from "@/api/patrol/project"

const taskRef = ref()
const { proxy } = getCurrentInstance()
const { patrol_date } = proxy.useDict('patrol_date')

const emits = defineEmits(['cancel', 'confirm'])

const userList = ref([])
const taskCycle = ref(false)
const form = ref({
  id: null,
  name: null,
  userId: null,
  startDate: null,
  endDate: null,
  patrolDate: [],
  startTime: null,
  endTime: null,
  companyId: null,
  lineId: [],
  busNoId: [],
  projectId: null,
  dateRange: null,
  timeRange: null,
  status: null
})
const rules = {
  name: [
    { required: true, message: "请输入任务名称", trigger: "blur" }
  ],
  userId: [
    { required: true, message: "请选择巡更人", trigger: "blur" }
  ],
  dateRange: [
    { required: true, message: "请选择任务周期", trigger: "blur" }
  ],
  patrolDate: [
    { required: true, message: "请选择巡更日期", trigger: "blur" }
  ],
  timeRange: [
    { required: true, message: "请选择巡更时间", trigger: "blur" }
  ],
  companyId: [
    { required: true, message: "请选择所属公司", trigger: "blur" }
  ],
  lineId: [
    { required: true, message: "请选择车辆线路", trigger: "blur" }
  ],
  busNoId: [
    { required: true, message: "请选择车辆编号", trigger: "blur" }
  ],
  projectId: [
    { required: true, message: "请选择巡更项目", trigger: "blur" }
  ]
}
const companyList = ref([])
const projectList = ref([])
const busNo = ref([])
const lineList = ref([])
const treeProps = {
  label: 'name',
  disabled: (data, node) => {
    return data.state == 2 || data.check == false
  }
}
const expandedKeys = ref([])
const projectStandard = ref('')

const pageInit = (id) => {
  if (id) {
    getPatrolTask(id).then(response => {
      form.value = response.data
      form.value.dateRange = [form.value.startDate,form.value.endDate]
      form.value.timeRange = [form.value.startTime,form.value.endTime]
      form.value.lineId = form.value.lineId.split(",")
      form.value.busNoId = form.value.busNoId.split(",")
      form.value.patrolDate = form.value.patrolDate.split(",")
      form.value.companyId = form.value.companyId
      expandedKeys.value = [form.value.companyId]
      getLine(form.value.companyId)
      getBusNo(form.value.lineId, 0)
      const currentDate = proxy.parseTime(new Date(), '{y}-{m}-{d}')
      taskCycle.value = currentDate >= form.value.startDate
      projectStandard.value = form.value.projectStandard
      getUserList()
    })
  }
}

const handleLineChange = (val) => {
  if (!val) {
    getBusNo(form.value.lineId, 1)
  }
}

const handleProjectChange = (val) => {
  const obj = projectList.value.find(item => {
    return item.id == val
  })
  projectStandard.value = obj.standard || ''
}

const handleDisabledDate = (date) => {
  date = proxy.parseTime(date, '{y}-{m}-{d}')
  const currentDate = proxy.parseTime(new Date(), '{y}-{m}-{d}')
  return date < currentDate
}

/** 巡更项目列表 */
function getProjectList() {
  const params = {
    pageNum: 1,
    pageSize: 200,
  }
  listPatrolProject(params).then(response => {
    response.rows.forEach(obj => {
      projectList.value.push(obj)
    })
  })
}

/** 公司列表 */
function getCompanyList() {
  getAllCompanies().then(res => {
    companyList.value = res.data || []
  })
}

function handleCompanyChange(val) {
  form.value.userId = null
  form.value.lineId = []
  form.value.busNoId = []
  getLine(val)
  getUserList()
}

/** 获取巡更人列表 */
function getUserList() {
  const params = {
    companyId: form.value.companyId
  }
  getSelectData(params).then(response => {
    userList.value = response.data.patrolUser
  })
}

function getLine(value) {
  const params = {
    companyId: value,
    pageNum: 1,
    pageSize: 200
  }
  listLine(params).then(response => {
    lineList.value = response.rows
  })
}

/** 获取车辆编号 */
function getBusNo(value, type) {
  let lineId = value.join(',')
  const data = {
    lineId
  }
  getSelectData(data).then(response => {
    if (type == 1) {
      form.value.busNoId = []
    }
    busNo.value = response.data.bus || []
  })
}

const onCancel = () => {
  emits('cancel')
}

const onConfirm = () => {
  taskRef.value.validate(valid => {
    if (valid) {
      const params = {
        ...form.value,
        lineId: form.value.lineId.join(','),
        busNoId: form.value.busNoId.join(','),
        patrolDate: form.value.patrolDate.join(','),
        startDate: form.value.dateRange[0],
        endDate: form.value.dateRange[1],
        startTime: form.value.timeRange[0],
        endTime: form.value.timeRange[1]
      }
      if (form.value.id ) {
        updatePatrolTask(params).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          emits('confirm')
        })
      } else {
        addPatrolTask(params).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          emits('confirm')
        })
      }
    }
  })
}

getCompanyList()
getProjectList()

defineExpose({
  pageInit
})

</script>

<style lang="scss" scoped>

</style>